package com.example.javapracticaltraining.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.javapracticaltraining.entity.R;
import com.example.javapracticaltraining.entity.pojo.CareLevel;
import com.example.javapracticaltraining.service.CareLevelService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 护理等级管理控制器
 */
@Tag(name = "护理等级管理", description = "提供护理等级的增删改查功能")
@RestController
@RequestMapping("/carelevels")
public class CareLevelController {

    @Autowired
    private CareLevelService careLevelService;

    /**
     * 获取所有护理等级
     * @return 护理等级列表
     */
    @Operation(summary = "获取所有护理等级", description = "获取系统中所有的护理等级信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "成功获取护理等级列表")
    })
    @GetMapping
    public R<List<CareLevel>> getAllCareLevels() {
        List<CareLevel> careLevels = careLevelService.list();
        return R.success(careLevels);
    }

    /**
     * 分页获取护理等级
     * @param page 页码
     * @param pageSize 每页大小
     * @param levelName 护理等级名称（可选，用于筛选）
     * @return 分页后的护理等级列表
     */
    @Operation(summary = "分页查询护理等级", description = "根据条件分页查询护理等级信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "成功获取护理等级分页列表")
    })
    @GetMapping("/page")
    public R<Page<CareLevel>> getCareLevelsByPage(
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页记录数", example = "10") @RequestParam(defaultValue = "10") int pageSize,
            @Parameter(description = "护理等级名称，支持模糊查询") String levelName) {
        // 创建分页对象，设置当前页和每页大小
        Page<CareLevel> pageInfo = new Page<>();
        pageInfo.setCurrent(page);
        pageInfo.setSize(pageSize);

        // 创建查询条件
        LambdaQueryWrapper<CareLevel> queryWrapper = new LambdaQueryWrapper<>();
        if (levelName != null && !levelName.isEmpty()) {
            queryWrapper.like(CareLevel::getLevelName, levelName);
        }

        // 执行分页查询
        careLevelService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 根据ID获取护理等级
     * @param levelId 护理等级ID
     * @return 护理等级信息
     */
    @Operation(summary = "获取护理等级详情", description = "根据ID获取护理等级详细信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "成功获取护理等级信息"),
        @ApiResponse(responseCode = "404", description = "未找到该护理等级")
    })
    @GetMapping("/{levelId}")
    public R<CareLevel> getCareLevel(
            @Parameter(description = "护理等级ID", required = true) @PathVariable Integer levelId) {
        CareLevel careLevel = careLevelService.getById(levelId);
        if (careLevel != null) {
            return R.success(careLevel);
        }
        return R.failure(404, "未找到该护理等级");
    }

    /**
     * 添加新的护理等级
     * @param careLevel 护理等级信息
     * @return 操作结果
     */
    @Operation(summary = "添加护理等级", description = "创建新的护理等级")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "护理等级添加成功"),
        @ApiResponse(responseCode = "400", description = "已存在同名护理等级")
    })
    @PostMapping
    public R<String> addCareLevel(@RequestBody CareLevel careLevel) {
        // 检查是否已存在同名护理等级
        LambdaQueryWrapper<CareLevel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CareLevel::getLevelName, careLevel.getLevelName());
        CareLevel existingLevel = careLevelService.getOne(queryWrapper);

        if (existingLevel != null) {
            return R.failure(400, "已存在同名护理等级");
        }

        careLevelService.save(careLevel);
        return R.success("护理等级添加成功");
    }

    /**
     * 更新护理等级信息
     * @param careLevel 护理等级信息
     * @return 操作结果
     */
    @Operation(summary = "更新护理等级", description = "根据ID更新护理等级信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "护理等级更新成功"),
        @ApiResponse(responseCode = "400", description = "护理等级ID不能为空或已存在同名护理等级"),
        @ApiResponse(responseCode = "404", description = "未找到该护理等级")
    })
    @PutMapping
    public R<String> updateCareLevel(@RequestBody CareLevel careLevel) {
        // 检查是否存在
        if (careLevel.getLevelId() == null) {
            return R.failure(400, "护理等级ID不能为空");
        }

        CareLevel existingLevel = careLevelService.getById(careLevel.getLevelId());
        if (existingLevel == null) {
            return R.failure(404, "未找到该护理等级");
        }

        // 检查是否已存在同名护理等级（排除自身）
        LambdaQueryWrapper<CareLevel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CareLevel::getLevelName, careLevel.getLevelName())
                   .ne(CareLevel::getLevelId, careLevel.getLevelId());
        CareLevel duplicateLevel = careLevelService.getOne(queryWrapper);

        if (duplicateLevel != null) {
            return R.failure(400, "已存在同名护理等级");
        }

        careLevelService.updateById(careLevel);
        return R.success("护理等级更新成功");
    }

    /**
     * 删除护理等级
     * @param levelId 护理等级ID
     * @return 操作结果
     */
    @Operation(summary = "删除护理等级", description = "根据ID删除护理等级")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "护理等级删除成功"),
        @ApiResponse(responseCode = "404", description = "未找到该护理等级")
    })
    @DeleteMapping("/{levelId}")
    public R<String> deleteCareLevel(
            @Parameter(description = "护理等级ID", required = true) @PathVariable Integer levelId) {
        // 检查是否存在
        CareLevel existingLevel = careLevelService.getById(levelId);
        if (existingLevel == null) {
            return R.failure(404, "未找到该护理等级");
        }



        careLevelService.removeById(levelId);
        return R.success("护理等级删除成功");
    }
}
